package wang.aweb.childcar.util;


import com.alibaba.fastjson.JSONObject;
import io.netty.handler.codec.http.HttpUtil;
import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import sun.net.www.http.HttpClient;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class WechatReqUtils {

    public static JSONObject getOpenIdByCode(String code,String appid,String appsecret) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> requestUrlParam = new HashMap<>();
        //小程序appId
        requestUrlParam.put("appid", appid);
        //小程序secret
        requestUrlParam.put("secret",appsecret);
        //小程序端返回的code
        requestUrlParam.put("js_code", code);
        //默认参数
        requestUrlParam.put("grant_type", "authorization_code");
        //发送post请求读取调用微信接口获取openid用户唯一标识
        String result = HttpClientUtil.doGet(requestUrl, requestUrlParam);
        JSONObject jsonObject= JSONObject.parseObject(result);
        return jsonObject;
    }
    public static String getAccessToken(String appid,String secret){
        RedissonClient client= Redisson.create();
        RBucket<String> bucket=client.getBucket("wxAccessToken");
        Boolean exists=bucket.isExists();
        if(exists){
            return bucket.get();
        }else{
            String requestUrl="https://api.weixin.qq.com/cgi-bin/token";
            Map<String, String> requestUrlParam = new HashMap<>();
            requestUrlParam.put("appid",appid);
            requestUrlParam.put("secret",secret);
            requestUrlParam.put("grant_type","client_credential");
            String result=HttpClientUtil.doGet(requestUrl,requestUrlParam);
            JSONObject res=JSONObject.parseObject(result);
            bucket.set(res.get("access_token").toString(),60*60*2, TimeUnit.SECONDS);
            return res.get("access_token").toString();
        }
    }
    public static JSONObject getPhone(String code, String appid, String appsecret) {
        String requestUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+getAccessToken(appid,appsecret);

        Map putMap=new HashMap();
        putMap.put("code",code);
        JSONObject mapJson=new JSONObject(putMap);
        //发送post请求读取调用微信接口获取openid用户唯一标识
        String result = HttpClientUtil.doPostJson(requestUrl, mapJson.toString());
        JSONObject jsonObject= JSONObject.parseObject(result);
        return jsonObject;
    }
}
